(function () {
    // var GetUrl = 'http://192.168.0.175:8082';
    // var GetUrl = 'http://192.168.0.25:5010/trueMAEC';
    var GetUrl = 'http://61.155.85.78:5012/trueMAEC';
    var deptid = '{BFA80019-0000-0000-432B-267E0000000E}';

    // 获取 wangEditor 构造函数和 jquery
    var E = window.wangEditor;
    var $ = window.jQuery;

    var idPrefix = 'tags_' + Math.random().toString().replace('.', '') + '_',
        globalNum = 1;

    function getUniqeId(){
        return idPrefix + (globalNum++); 
    }

    $('#twEditor').append('<div id="chartTem"></div>').append('<div id="chartParamWrap"></div>')
        .append('<div style="margin:20px;" id="chartWrap"></div>').find("#chartWrap")
        .append('<div class="JS_tableWrap"></div>')
        .append('<div class="JS_groupWrap"></div>')
        .append('<div class="JS_fieldWrap"></div>')
        .append('<div class="JS_conditionWrap"></div>')
        .append('<div class="JS_paramWrap"></div>')
        .append('<div class="JS_setWrap"></div>')
        // .append('<div class="JS_functionWrap"></div>')
        // .append('<div class="JS_styleWrap"></div>')
        // .append('<div class="JS_resultWrap"></div>')
        .append('<div class="JS_relateWrap"></div>');

    var $chartTableWrap      = $('#chartWrap .JS_tableWrap');
    var $chartFieldWrap      = $('#chartWrap .JS_fieldWrap');
    var $chartParamWrap      = $('#chartWrap .JS_paramWrap');
    var $chartGroupWrap   = $('#chartWrap .JS_groupWrap');
    var $chartConditionWrap           = $('#chartWrap .JS_conditionWrap');
    var $chartSetWrap     = $('#chartWrap .JS_setWrap');
    var $chartRelateWrap     = $('#chartWrap .JS_relateWrap');
    var $chartComWrap        = $('#chartWrap .JS_comWrap');

    

    // 清空
    function clearChartsWrap(){
        $chartTableWrap.html('');
        $chartFieldWrap.html('');
        $chartParamWrap.html('');
        $chartComWrap.html('');
        // $chartFunctionWrap.html('');
        // $styleWrap.html('');
        // $chartResultWrap.html('');
    }


    function getChartModelList(){
        $.ajax({
            type:"POST",
            dataType:"jsonp",
            jsonp:"callback",
            url: GetUrl + "/trueDataController/getModelList.do?deptid="+deptid,
            cache: false,
            async: false,
            success:function(msg){
                var tables = msg.data;

                var tableOption = '<option>请选择指标</option>';
                for(key in tables){
                    tableOption += '<option value='+ tables[key].modelId +' data-tableName="'+ tables[key].tableName +'">'+tables[key].modelName+'</option>';
                }
                // 生成来源表
                var $tableItem = $('<div class="form-inline" style="margin-bottom:10px"><div class="form-group"><label>选择指标: </label><select class="form-control input-sm">'+ tableOption +'</select></div></div>');  
                $chartTableWrap.html('').append($tableItem);


                $chartTableWrap.on('change', 'select', function(){
                    var modelId = $(this).val();

                    var groupTable = ''
                    for(key in tables){
                        if(tables[key].modelId == modelId){
                            var tabelName = tables[key].tableName;
                            var groups = tables[key].tyzdxList;

                            var groupItem = '';
                            for( i in groups ){
                                // "name": "南通市区组",
                                var groupHD = groups[i].name;
                                var groupId = groups[i].id;
                                var groupBD = '';
                                var mxs = groups[i].mxlist;
                                for (j in mxs){
                                    groupBD += '<span class="label-item" data-guid="'+ mxs[j].guid +'">'+ mxs[j].zbmc +'</span>';

                                }
                                groupItem += '<tr data-tablename="'+ tabelName +'" ><th>'+ groupHD +'</th><td>'+ groupBD +'</td></tr>'

                            }

                        }
                    }
                    groupTable = $('<table data-modelId="'+modelId+'" class="table table-bordered"><colgroup><col width="15%"></colgroup>'+ groupItem +'</table>');
                    $chartGroupWrap.html('').append(groupTable);

                    var fieldTable = '';
                    $.ajax({
                        type:"POST",
                        dataType:"jsonp",
                        jsonp:"callback",
                        url: GetUrl + "/trueDataController/getFieldList.do?modelId="+modelId,
                        cache: false,
                        async: false,
                        success:function(field){
                            var fields = field.data.fields;
                            var fieldItem = ''
                            for(f in fields){
                                fieldItem += '<span class="label-item" data-paramid="_t'+ f +'" data-fieldname="'+ fields[f].name +'">'+ fields[f].note +'</span>'
                            }
                            fieldTable = $('<table class="table table-bordered"><colgroup><col width="15%" /></colgroup><tr><th>选择要素</th><td>'+ fieldItem +'</td></tr></table>');
                            $chartFieldWrap.html('').append(fieldTable);
                        }
                    })


                    var conditionTable = '';
                    var $condItem = $('<div class="form-inline" style="margin-bottom:10px"><div class="form-group"><label>选择时间: </label><select class="form-control input-sm JS_conditionDate"><option>选择时间</option><option value="year">年度</option><option value="month">月度</option><option value="quarter">季度</option></select><div style="display:inline-block" class="JS_conditionDateS"></div></div></div>');  
                    
                    var condYearOption = '';
                    var condMonthOption = '';
                    for ( var i = 2015; i<=2020; i++ ){
                        condYearOption += '<option value ="'+ i +'">'+ i +'</option>';
                    }
                    for ( var i = 1; i<=12; i++ ){
                        condMonthOption += '<option value ="'+ i +'">'+ i +'</option>';
                    }
                    var conQuarterOption = '<option value="1">第一季度</option><option value="2">第二季度</option><option value="3">第三季度</option><option value="4">第四季度</option>'
                    
                    $chartConditionWrap.html('').append($condItem);
                    var condYearSelect =$('<select class="form-control input-sm JS_condYear">'+ condYearOption +'</select>');
                    var condMonthSelect = $('<select class="form-control input-sm JS_condYear">'+ condYearOption +'</select><select class="form-control input-sm JS_condMonth">'+ condMonthOption +'</select>');
                    var condQuarterSelect = $('<select class="form-control input-sm JS_condYear">'+ condYearOption +'</select><select class="form-control input-sm JS_condQuarter">'+ conQuarterOption +'</select>');
                    $chartConditionWrap.on('change', ".JS_conditionDate", function(){
                        var conditionType = $(this).val();
                        if(conditionType == 'year'){
                            $chartConditionWrap.find(".JS_conditionDateS").html("").append(condYearSelect);
                        } else if(conditionType == 'month'){
                            $chartConditionWrap.find(".JS_conditionDateS").html("").append(condMonthSelect);
                        } else if(conditionType == 'quarter'){
                            $chartConditionWrap.find(".JS_conditionDateS").html("").append(condQuarterSelect);
                        }
                    })

                    $chartSetWrap.html("").append('<span class="JS_btnChartSetting btn btn-primary btn-xs">配置图表</span>')

                    // $tagResultWrap.html("").append('<p>结果预览：<span class="JS_btnTagTest btn btn-primary btn-xs">测试</span> <span class="JS_tagValue tags"></span></p>');

                    // $functionWrap.html("").append('<p><span>计算公式：</span><input class="JS_inputResult" type="text" placeholder="计算公式" /></p>');
                })

            }
        })
    }


    $chartFieldWrap.on("click", ".label-item", function(){
        // $fieldWrap.find('.label-item').removeClass('checked');
        $(this).toggleClass('checked');
        // var paramKey = $(this).attr("data-paramid")
        // $functionWrap.find('input').val(paramKey);
    })

    $chartGroupWrap.on("click", ".label-item", function(){
        // $groupWrap.find('.label-item').removeClass('checked');
        $(this).toggleClass('checked');
    })





   
    var chartJSON = new Object;
    // 生成chart json
    function creatChartJSON(){

        // var params = $chartParamWrap.find(".param-item");
        paramJSON = new Array;

        // var _tableName = $groupWrap.find("table").attr('data-tablename');
        // var _groupId = $groupWrap.find("table").attr('data-modelId');


        // var joinJson = {"join": [{ "condition": { "t_nttj_data_2016.mxzbid": "=t_nttj_fbgl_zbgl_mxxx.guid" }, "connect": "left join", "table": "t_nttj_data_2016,t_nttj_fbgl_zbgl_mxxx"}]}

        // var groups = $groupWrap.find(".label-item.checked");

        // groups.each(function() {
            
        // });


        
        // var _guId = group.attr('data-guid');

        // var _year = $conditionWrap.find('select.JS_condYear').val();
        // var _month = $conditionWrap.find('select.JS_condMonth').val();
        // var _quarter = $conditionWrap.find('select.JS_condQuarter').val();

        // _year = typeof _year != 'undefined' ? "='"+_year+"'" : "";
        // _month = typeof _month != 'undefined' ? "='"+_month+"'" : "";
        // _quarter = typeof _quarter != 'undefined' ? "='"+_quarter+"'" : "";





        // params.each(function(){
        //     var _this = $(this);
        //     var _tableName      = _this.attr('data-tablename');
        //     var fieldObj = _this.find(".field-item");
        //     var fieldLen = fieldObj.length;
        //     var _field ='';
        //     var _note ='';
        //     fieldObj.each(function(index){
        //         var _fieldName      = $(this).attr('data-fieldname');
        //         var _noteName = $(this).text();
        //         _field += fieldLen == index+1 ? _fieldName :  _fieldName+ ',';
        //         _note += fieldLen == index+1 ? _noteName : _noteName + ',';

        //     })

        //     var conditionsObj   = _this.find(".condition-item");
        //     var _condition = {};
        //     conditionsObj.each(function() {
        //         var _conFieldName = $(this).find('.JS_conditionField').find(':selected').val();
        //         var _conFieldRelate = $(this).find('.JS_conditionRelate').find(':selected').val();
        //         var _conFieldValue = $(this).find('.JS_conditionValue').find(':selected').val();
        //         var _conCondition = _conFieldRelate + "'"+ _conFieldValue + "'";
        //         if(!_conFieldName == ''){
        //             if(typeof _condition[_conFieldName] == 'undefined'){
        //                 _condition[_conFieldName] = _conCondition;
        //             }else{
        //                 _condition[_conFieldName] = _condition[_conFieldName]+'||'+_conCondition;
        //             }
        //         }
        //     });
        //     var _paramItem = {'table': _tableName, 'field':_field, 'note':_note, 'condition':_condition};
        //     paramJSON.push(_paramItem);
        // })

        // var modelJSON = new Array;
        // var models = $chartFieldWrap.find(".table-item");
        // models.each(function(){
        //     var t = $(this).attr('data-modelId');
        //     modelJSON.push(t);
        // })

        // chartJSON = {'param' : paramJSON, 'models':modelJSON, 'type': 2};

        chartJSON = {"join":[{"condition":{"t_nttj_data_2016.mxzbid":"=t_nttj_fbgl_zbgl_mxxx.guid"},"connect":"left join","table":"t_nttj_data_2016,t_nttj_fbgl_zbgl_mxxx"}],"param":[{"condition":{"mxzbid":" in('36e6d352-3be2-4cb0-bc3f-3fb8b135698c', '86988c95-8379-44f7-946c-c966d66bac82', '9971cde0-4ead-4b2f-9d8b-88650adf8e15', '373f5ce9-6e09-40ca-bffa-d1ab484bf4f7', '14c3738b-8b76-4a19-82c9-0f42942e9645', 'b4760538-0bea-4fdb-b356-ed2c973bcd78', 'a130b2b7-1ebe-4635-8e69-bc54a9b21dd5', '5f18710c-dec3-4cb5-bb1b-339dc1f74b48', '4386bf22-fefa-4f4a-bf3c-2194418b122c', 'cf9b17f6-146f-416d-ac18-676e89f922e9', '799600de-b714-4ceb-82e3-8e30a7c90abc', '72a68ce1-3120-465b-9e50-cb381f55193b')","zbid":"='cc94ad22-824a-411a-8025-372da9e45cae'","month":"","year":"='2016'","season":"='1'"},"field":"zl,zf","note":"总量,增幅","table":"t_nttj_data_2016"},{"condition":{},"field":"zbmc","note":"指标名称","table":"t_nttj_fbgl_zbgl_mxxx"}],"type":"2"}
        // var paramItem = {};
        // paramItem[_paramId] = _paramItem;

        // $paramConditionItem = $('<span class="JS_btnDelParam delparam"><i class="fa fa-close"></i></span><span>'+ _paramId +'</span><textarea style="display:none">'+ JSON.stringify(paramItem) + '</textarea>');
        // paramKey = _paramId;

        console.log(JSON.stringify(chartJSON));
    }


    // 点击选择取值字段
    $chartFieldWrap.on("click", ".field-item", function(){
        if($(this).hasClass('checked')) return;
        $(this).addClass('checked');
        
        var tableName   = $(this).parents(".table-item").attr("data-tableName");
        var fieldName   = $(this).attr("data-fieldName");
        var fieldNote   = $(this).text();


        var $paramItem      = $('<span data-fieldname="'+ fieldName +'" class="field-item">'+ fieldNote +'</span>')

        var $trParamItem    = $('<tr class="param-item" data-tablename="'+ tableName +'"><td class="JS_chartField"><span data-fieldname="'+ fieldName +'" class="field-item">'+ fieldNote +'</span></td><td class="JS_chartFieldCondition" style="padding:0"><table class="condition-wrap table" style="margin-bottom:0"><tr><td colspan="2"><span class="JS_addCondition btn btn-primary btn-xs">添加条件</span></td></tr></table></td></tr>');


        var $conditionTable = $('<table class="condition-wrap table" style="margin-bottom:0"><tr><td colspan="2"><span class="JS_addCondition btn btn-primary btn-xs">添加条件</span></td></tr></table>');

        // 插入table
        if(!$chartParamWrap.find("table").length){
            $chartParamWrap.append('<table class="JS_cparamWrap table table-bordered">'+
                '<colgroup><col width="40%"></colgroup>'+
                '<thead><th>字段</th><th>筛选条件</th></thead>'+
                '<tbody></tbody>'+
                '<tfoot><tr><td colspan="2"><span class="JS_btnChartSetting btn btn-primary btn-xs">配置图表</span></td></tr></tfoot>'+
                '</table>'+
                '<div class="form-inline">'+
                '<div class="form-group"><label for="">宽度：</label><input type="text" class="form-control input-sm JS_chartWidth" id="" placeholder="" value="400"></div>'+
                '<div class="form-group"><label for="">高度：</label><input type="text" class="form-control input-sm JS_chartHeight" id="" placeholder="" value="300"></div></div>');
        }

        var trs = $chartParamWrap.find(".param-item");
        if(!trs.length){
            $chartParamWrap.find('tbody').append($trParamItem);
            // $chartParamWrap.find(".JS_chartFieldCondition").append($conditionTable);
        }else{

            var tableJSON = new Array;
            var tables = $chartFieldWrap.find(".table-item");
            trs.each(function(){
                var t = $(this).attr('data-tablename');
                tableJSON.push(t);
            })
            // 避免重复表
            if($.inArray(tableName, tableJSON) == -1){

                // getFields(modelId);
                $chartParamWrap.find('>table>tbody').append($trParamItem);

            }else{
                trs.each(function() {
                    if($(this).attr("data-tablename") == tableName){
                        $(this).find(".JS_chartField").append($paramItem);
                    }
                })
            }

        }
        
    })


    var conditionSelect = '<select class="JS_conditionRelate">'+
        '<option value="=">=</option>'+
        '<option value=">">></option>'+
        '<option value=">=">>=</option>'+
        '<option value="<"><</option>'+
        '<option value="<="><=</option>'+
        '<option value="in">包含</option>'+
        '</select>';

    $chartParamWrap.on('change', '.JS_conditionField', function(){
        var fieldName = $(this).val();
        var tableName = $(this).parents(".param-item").attr("data-tablename");
        var _this = $(this);
        var columnSelect = _this.parent('td').find(".JS_conditionValue");
        columnSelect.html('');
        $.ajax({
            type:"POST",
            dataType:"jsonp",
            jsonp:"callback",
            url: GetUrl + "/trueDataController/columnVal.do?table="+tableName+"&column="+fieldName,
            cache: false,
            async: false,
            success:function(msg){
                var values = msg.data;
                console.log(values)
                var fieldOption = '';
                for(key in values){
                    columnSelect.append(new Option(values[key], values[key]));
                }
            }
        });
    })


    // 添加条件字段
    $chartParamWrap.on('click', '.JS_addCondition', function(){
        var tableName   = $(this).parents(".param-item").attr("data-tableName");
        getTableOption(tableName);
        var $conditionItem = $('<tr class="condition-item"><td><select class="JS_conditionField">'+ fieldOption +'</select>'+ conditionSelect +'<select class="JS_conditionValue" id=""></select></td><td><span class="JS_delCondition btn btn-danger btn-xs">删除条件</span></td></tr>')
        $(this).closest('tr').before($conditionItem);
        // $chartParamWrap.find(".JS_chartFieldCondition table").find('tr:last').before($conditionItem);
    })

    $chartParamWrap.on('click', '.JS_delCondition', function(){
        $(this).closest('tr').remove();
    })

   

    // 图表配置
    $chartSetWrap.on("click", ".JS_btnChartSetting", function(){
        creatChartJSON();
        var a = JSON.stringify(chartJSON);
        console.log(a)
        $.ajax({
            type:"POST",
            data:a,
            dataType:"jsonp",
            jsonp:"callback",
            url:GetUrl + "/formulaController/getResult.do?function="+a,
            success:function(msg){
                var val;
                if(msg.success){
                    val = msg.data;
                    console.log(val)
                    var dd = JSON.stringify(val);
                    var url = GetUrl + "/trueDataController/online.do?data="+encodeURIComponent(dd);

                    // var url = "http://61.155.85.74:3333/TrueDPS/trueDataController/online.do?data="+encodeURIComponent(dd);

                    


                    // var url = '/TrueReport/report/data/demo/online.html'
                    layer.open({
                        type: 2,
                        area: ['800px', '550px'],
                        title: '配置图表', 
                        content: url
                    })

                }else{
                    val = msg.error;
                    layer.alert(val);
                }

                       
            }
        });
    })



    // 创建chart 标签
    E.createMenu(function (check) {
    
        var menuId = 'chart';
        if (!check(menuId)) {
            return;
        }
        var editor = this;
        
        // 创建 menu 对象
        var menu = new E.Menu({
            editor: editor,
            id: menuId,
            title: '插入图表',

            // 正常状态和选中装下的dom对象，样式需要自定义
            $domNormal: $('<a href="#" tabindex="-1"><i class="wangeditor-custom-icon-chart"></i></a>'),
            $domSelected: $('<a href="#" tabindex="-1" class="selected"><i class="wangeditor-custom-icon-chart"></i></a>')
        });

        // 点击菜单
        menu.clickEvent = function (e) {
            // 清空弹框内容
            clearChartsWrap();
            // 获取表数据
            // getModelList();
            // getChartScource();

            getChartModelList()
            layer.open({
                type: 1,
                area: ['800px', '550px'],
                title: '插入图表', 
                content: $('#chartWrap'), 
                btn: ['确定', '取消'],
                yes: function(index, layero){
                    var sourceId = $chartTableWrap.find('.JS_chartSource').val();
                    var chartId = getUniqeId();
                    var optionChart,
                    chart,
                    chartW,
                    chartH;
                    
                        creatChartJSON();
                        var a = JSON.stringify(chartJSON);
                        optionChart = $(layero).find('.JS_optionChart').val();
                        var optionChartGroup = $(layero).find('.JS_optionChartGroup').val();
                        chartW = $(layero).find('.JS_chartWidth').val();
                        chartH = $(layero).find('.JS_chartHeight').val();
                        chart = '<div class="charts" style="width:400px; height:400px"><span class="chartjson"><!--TrueDATA['+ a +']--></span><span class="chartoptiongroup"><!--TrueChgp['+ optionChartGroup +']--></span><div class="chart-box" style="width:400px; height:400px" id="'+chartId+'"></div></div>';
                    
                    
                    
                    
                    
                    
                    editor.command(e, 'insertHtml', chart);

                    var chartItem = echarts.init(document.getElementById(chartId));
                    chartItem.setOption(JSON.parse(optionChart));
                    
                    layer.close(index);

                           
                }
            });
        }

        // 增加到editor对象中
        editor.menus[menuId] = menu;
    });

    // tag toolbar
    E.plugin(function () {
        var editor = this;
        var txt = editor.txt;
        var $txt = txt.$txt;
        // 说明：设置了 max-height 之后，$txt.parent() 负责滚动处理
        var $currentTxt = editor.useMaxHeight ? $txt.parent() : $txt;
        var $currentTag;

        // 用到的dom节点
        var isRendered = false;
        var $toolbar = $('<div class="txt-toolbar"></div>');
        var $triangle = $('<div class="tip-triangle"></div>');
        var $delete = $('<a href="#"><i class="wangeditor-menu-img-trash-o"></i></a>');
        var $edit = $('<a href="#"><i class="wangeditor-custom-icon-edit"></i></a>');
        //id前缀
        

        // 渲染到页面
        function render() {
            if (isRendered) {
                return;
            }
            
            // 绑定事件
            bindEvent();

            // 拼接 渲染到页面上
            $toolbar.append($triangle)
                    .append($delete)
                    .append($edit);
            editor.$editorContainer.append($toolbar);
            isRendered = true;
        }

        // 绑定事件
        function bindEvent() {
            // 统一执行命令的方法
            var commandFn;
            function command(e, callback) {
                if (commandFn) {
                    editor.customCommand(e, commandFn, callback);
                }
            }

            // 删除
            $delete.click(function (e) {
                commandFn = function () {
                    $currentTag.remove();
                };
                command(e, function () {
                    setTimeout(hide, 100);
                });
            });

            $edit.click(function(e) {
                // var random = E.random();
                // var rangeElem = editor.getSelfOrParentByName('i','tags');
                // console.log(rangeElem);

                var ct = $currentTag;

                if(ct.hasClass('chartCom')){
                    alert('staic');
                    getChartScource();
                    $chartComWrap.html('');
                    $chartTableWrap.find('.JS_chartSource').val('1').trigger('change');
                    var comId = ct.attr('data-comid');
                    
                    $chartTableWrap.find('.JS_componentList').val(comId);
                    getComponent(comId)
                }else{



                    var chart ='';

                    var chartlabel = $.trim($currentTag.find(".chartjson").html());
                    chart = JSON.parse(chartlabel.slice(13,chartlabel.length-4));

                    clearChartsWrap()

                    // 获取表数据
                    getModelList();

                    for(key in chart.models ){ 
                        var modelId = chart.models[key];
                        getFields(modelId);
                    }

                    $chartParamWrap.append('<table class="JS_cparamWrap table table-bordered">'+
                        '<colgroup><col width="40%"></colgroup>'+
                        '<thead><th>字段</th><th>筛选条件</th></thead>'+
                        '<tbody></tbody>'+
                        '<tfoot><tr><td colspan="2"><span class="JS_btnChartSetting btn btn-primary btn-xs">配置图表</span></td></tr></tfoot>'+
                        '</table>'+
                        '<div class="form-inline">'+
                        '<div class="form-group"><label for="">宽度：</label><input type="text" class="form-control input-sm JS_chartWidth" id="" placeholder="" value="400"></div>'+
                        '<div class="form-group"><label for="">高度：</label><input type="text" class="form-control input-sm JS_chartHeight" id="" placeholder="" value="300"></div></div>');

                    var tables = chart.param;

                    // "table": "T_CMS_DATA_YIBANGONGGONGYUSUAN",
                    // "field": "DiQu,ZongLiang,ZongLiangPaiMing,ZengFu,",
                    // "note": "地区,总量,总量排名,增幅,",
                    // "condition": {
                    //     "DiQu": "='徐州市'"
                    // }
                    var $trParamItem = ''
                    for(key in tables){
                        var tableName = tables[key].table;
                        var fields = tables[key].field.split(',');
                        var notes = tables[key].note.split(',');
                        var conditions = tables[key].condition;
                        var $paramItem  ='';
                        for(i in fields){
                            $paramItem += ('<span data-fieldname="'+ fields[i] +'" class="field-item">'+ notes[i] +'</span>') 
                        }
                        // var $paramItem      = $('<span data-fieldname="'+ fieldName +'" class="field-item">'+ fieldNote +'</span>')

                        $.each(conditions, function(j, value){
                            var fieldCondition = Object.keys(value)[0];
                        })


                        $trParamItem    = $('<tr class="param-item" data-tablename="'+ tableName +'"><td class="JS_chartField">'+ $paramItem +'</td><td class="JS_chartFieldCondition" style="padding:0"><table class="condition-wrap table" style="margin-bottom:0"><tr><td colspan="2"><span class="JS_addCondition btn btn-primary btn-xs">添加条件</span></td></tr></table></td></tr>');


                    }

                    $.each(chart.param, function(key, value){
                        var paramKey = Object.keys(value)[0];

                        $paramConditionItem = $('<div class="paramval-item"><span class="JS_btnDelParam delparam"><i class="fa fa-close"></i></span><span>'+ paramKey +'</span><textarea style="display:none">'+ JSON.stringify(value) + '</textarea></div>');
                        $chartParamWrap.append($paramConditionItem);
       
                    });
                    $chartParamWrap.find('tbody').append($trParamItem);

                    // var paramKey = chart.result.tag;
                    // setFunction(paramKey);
                }
                layer.open({
                    type: 1,
                    area: ['800px', '400px'],
                    title: '修改图表', 
                    content: $('#chartWrap'), 
                    btn: ['确定', '取消'],
                    yes: function(index){
                        creatTagJSON();
                        var a = JSON.stringify(chartJSON);
                        $.ajax({
                            type:"POST",
                            data:a,
                            dataType:"jsonp",
                            jsonp:"callback",
                            url:GetUrl + "/formulaController/getResult.do?function="+a,
                            success:function(msg){
                                var val;
                                if(msg.success){
                                    val = msg.data[0].tag;
                                }else{
                                    val = msg.error;
                                }
                                $chartResultWrap.find(".JS_tagValue").text(val);           
                            }
                        });
                    },
                    btn2: function(index){
                        creatTagJSON();
                        var tagId = getUniqeId();
                        var a = JSON.stringify(tagJSON);
                        var tagTem =  '<textarea style="display:none" id="'+tagId+'">'+a+'</textarea>'
                        var tagValue = $chartResultWrap.find(".JS_tagValue").text();
                        $("#tagTem").append(tagTem);
                        var s = '<i class="tags" data-id="'+ tagId +'">'+ tagValue +'</i>';
                        layer.close(index);
                        // 执行命令
                        // $currentTag.remove();
                        ct.remove();

                        editor.command(e, 'insertHtml', s);         
                    },
                    btn3: function(index){
                        layer.close(index);
                    }
                })

            });

            
        }

        // 显示 toolbar
        function show() {
            if (editor._disabled) {
                // 编辑器已经被禁用，则不让显示
                return;
            }
            if ($currentTag == null) {
                return;
            }
            $currentTag.addClass('clicked');
            var tagPosition = $currentTag.position();
            var tagTop = tagPosition.top;
            var tagLeft = tagPosition.left;
            var tagHeight = $currentTag.outerHeight();
            var tagWidth = $currentTag.outerWidth();

            // --- 定位 toolbar ---

            // 计算初步结果
            var top = tagTop + tagHeight;
            var left = tagLeft;
            var marginLeft = 0;

            var txtTop = $currentTxt.position().top;
            var txtHeight = $currentTxt.outerHeight();
            if (top > (txtTop + txtHeight)) {
                // top 不得超出编辑范围
                top = txtTop + txtHeight;
            }

            // 显示（方便计算 margin）
            $toolbar.show();

            // 计算 margin
            var width = $toolbar.outerWidth();
            marginLeft = tagWidth / 2 - width / 2;

            // 定位
            $toolbar.css({
                top: top + 5,
                left: left,
                'margin-left': marginLeft
            });
            // 如果定位太靠左了
            if (marginLeft < 0) {
                // 得到三角形的margin-left
                $toolbar.css('margin-left', '0');
                $triangle.hide();
            } else {
                $triangle.show();
            }
        }
        
        // 隐藏 toolbar
        function hide() {
            if ($currentTag == null) {
                return;
            }
            $currentTag.removeClass('clicked');
            $currentTag = null;
            $toolbar.hide();
        }

        // click tag 事件
        $currentTxt.on('click', '.charts', function (e) {
            var $tag = $(e.currentTarget);

            // 渲染
            render();

            if ($currentTag && ($currentTag.get(0) === $tag.get(0))) {
                setTimeout(hide, 100);
                return;
            }

            // 显示 toolbar
            $currentTag = $tag;
            show();

            // 阻止冒泡
            e.preventDefault();
            e.stopPropagation();
            
        }).on('click keydown scroll', function (e) {
            setTimeout(hide, 100);
        });
        E.$body.on('click keydown scroll', function (e) {
            setTimeout(hide, 100);
        });
    });



})();